import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  const token = ref('')
  const userInfo = ref(null)
  
  // 登录方法
  const login = async (credentials) => {
    try {
      const res = await loginApi(credentials)
      token.value = res.data.token
      // 存储到本地
      uni.setStorageSync('token', res.data.token)
      return res
    } catch (error) {
      throw error
    }
  }
  
  // 登出方法
  const logout = () => {
    token.value = ''
    userInfo.value = null
    uni.removeStorageSync('token')
    uni.removeStorageSync('userInfo')
  }
  
  // 检查登录状态
  const checkLogin = () => {
    if (!token.value) {
      const localToken = uni.getStorageSync('token')
      if (localToken) {
        token.value = localToken
        userInfo.value = uni.getStorageSync('userInfo')
      }
    }
    return !!token.value
  }
  
  return {
    token,
    userInfo,
    login,
    logout,
    checkLogin
  }
})